package com.scs.application.modules.wm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.BeanUtils;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.modules.cfg.utils.ParameterUtils;
import com.scs.application.modules.wm.entity.StockHistory;
import com.scs.application.modules.wm.entity.StockSettlement;
import com.scs.application.modules.wm.mapper.StockSettlementMapper;
import com.scs.application.modules.wm.service.StockHistoryService;
import com.scs.application.modules.wm.service.StockSettlementService;
import org.joda.time.LocalDateTime;
import org.joda.time.Months;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 */
@Service
public class StockSettlementServiceImpl extends BaseServiceImpl<StockSettlementMapper, StockSettlement> implements StockSettlementService {

    @Autowired
    private StockHistoryService stockHistoryService;

    @Override
    public String getStockSettlement() {
        String stockSettlementPush = ParameterUtils.getStockSettlementPush();
        if (stockSettlementPush.equals("0")) {
            return null;
        }
        Map < String, Object> map = this
                .getMap(new QueryWrapper<StockSettlement>()
                        .select("  DATE_FORMAT(IFNULL(MAX(back_date),'"+stockSettlementPush+"'),'%Y-%m-%d')  AS maxDate"));
        String maxDate = (String) map.get("maxDate");
        int months = Months.monthsBetween(LocalDateTime.parse(maxDate), LocalDateTime.now()).getMonths();
        for (int i = 0; i < months; i++) {
            Date addMonths = DateUtils.addMonths(DateUtils.parse(maxDate), i + 1);
            if (addMonths.after(new Date())) continue;
            this.saveStockSettlement(addMonths);
        }
        return null;
    }

    private void saveStockSettlement(Date addMonths) {
        String format = DateUtils.format(addMonths, "yyyy-MM-dd");
        List<StockHistory> stockHistories = this.stockHistoryService
                .list(new QueryWrapper<StockHistory>().eq("back_date", format).ne("sku_qty", 0));
        if (stockHistories != null && !stockHistories.isEmpty()) {
            List<StockSettlement> stockSettlements = new ArrayList<>();
            for (StockHistory stockHistory : stockHistories) {
                StockSettlement stockSettlement = new StockSettlement();
                BeanUtils.copyProperties(stockHistory, stockSettlement);
                stockSettlements.add(stockSettlement);
            }
            if (!stockSettlements.isEmpty()) {
                this.saveBatch(stockSettlements);
            }
        }

    }
}
